package com.design_patterns.memento;

import java.io.*;
import java.util.Objects;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-09-19 18:53
 **/

/**
 * 备忘录模式
 * 存储的对象 (Person) 必须实现  Serializable 接口
 */
public class Main {

    public static void main(String[] args) {
        File file = new File("src/main/resources/memento.txt");
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream inputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
            Person person = new Person();
            person.setId(1);
            objectOutputStream.writeObject(person);
            System.err.println(person);
            person.setId(2);
            System.err.println(person);
            inputStream = new ObjectInputStream(new FileInputStream(file));
            Person loadPerson = (Person) inputStream.readObject();
            System.err.println(loadPerson.toString());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                Objects.requireNonNull(objectOutputStream).close();
                Objects.requireNonNull(inputStream).close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
